var currentUniqueId = 0;


function getUniqueId() {
    // Should be more or less thread-safe since is uses the private state only.
    // However, MIGHT break if the same person opens the gadget in several
    // windows and clicks in each of them more or less at the same time...
    var privateState = wave.getPrivateState();

    var id = privateState.get('unique_id', -1);
    id = Math.max(id, currentUniqueId);

    id++;

    privateState.submitValue('unique_id', id);

    currentUniqueId = id;

    return numberToSortableString(id);
}

function numberToSortableString(id) {
    var result = '';

    while (id > 26) {
	result += 'Z';
	id -= 26;
    }

    result += String.fromCharCode(64 + id);

    return result;
}

function getIdSelector(id) {
    return "[id='" + id + "']";
}


function getWaveViewerId() {
    return wave.getViewer().getId();
}

/**
 * Check if the viewer is also the host, i.e. if they added the gadget to the
 * wave.
 * 
 * @return true if the viewer is the host, false otherwise.
 */
function isWaveHost() {
    var hostId = wave.getHost().getId();
    var viewerId = getWaveViewerId();
    var viewerIsWaveHost = (hostId == viewerId);
    return viewerIsWaveHost;
}


function escapeHtml(rawText) {
    // TODO: Is there a smarter way to do this?
    var textNode = document.createTextNode(rawText);
    span = document.createElement("span");
    span.appendChild(textNode);
    return span.innerHTML;
}
